package org.bravo369.inflightxt.utils;

import java.util.Vector;

public class Repository {
  private Vector<Position> positions;
  private long lastUpdate;
  private long lastUpload;
  private PositionUploader uploader;

  public Repository() {
    positions = new Vector<Position>();
    lastUpdate = 0;
    lastUpload = 0;
  }

  private void checkUpload() {
    Globals globals = Globals.getInstance();
    long currentTime = System.currentTimeMillis();
    if (globals.mode == Globals.SyncMode.NO_SYNC_TO_SERVER)
      return;
    if (lastUpload == 0) {
      lastUpload = currentTime;
      return;
    }
    else if (uploader != null && uploader.isAlive()) {
      return;
    }
    else if (positions.size() != 0 && (currentTime - lastUpload) > globals.serverUpdateRate) {
      Vector<Position> uploadPositions = new Vector<Position>();
      Position lastPosition = positions.lastElement();
      positions.remove(lastPosition);
      for (Position position: positions) {
        uploadPositions.add(position);
      }
      positions.clear();
      positions.add(lastPosition);
      uploader = new PositionUploader(uploadPositions);
      uploader.start();
      lastUpload = currentTime;
    }
  }

  private Position getCurrentPosition() {
    long currentTime = System.currentTimeMillis();
    Globals globals = Globals.getInstance();
    Position currentPosition = null;
    checkUpload();
    if (positions.isEmpty()) {
      currentPosition = new Position();
      currentPosition.session = globals.currentSession;
      currentPosition.timestamp = System.currentTimeMillis();
    }
    if ((currentTime - lastUpdate) > globals.dataRefreshRate) {
      if (!positions.isEmpty()) {
        // Initialize the current position to the last position values.
        currentPosition = new Position();
        Position lastElement = positions.lastElement();
        currentPosition.latitude = lastElement.latitude;
        currentPosition.longitude = lastElement.longitude;
        currentPosition.altitude = lastElement.altitude;
        currentPosition.pitch = lastElement.pitch;
        currentPosition.roll = lastElement.roll;
        currentPosition.heading = lastElement.heading;
        currentPosition.session = globals.currentSession;
        currentPosition.timestamp = System.currentTimeMillis();
      }
      positions.add(currentPosition);
      lastUpdate = currentTime;
    }
    else {
      currentPosition = positions.lastElement();
    }
    return currentPosition;
  }

  public void addGpsData(Double lat, Double lon, Double alt) {
    Position currentPosition = getCurrentPosition();
    currentPosition.latitude = lat;
    currentPosition.longitude = lon;
    currentPosition.altitude = alt;
  }

  public void addTiltData(float pitch, float roll, float heading) {
    Position currentPosition = getCurrentPosition();
    currentPosition.pitch = (double) pitch;
    currentPosition.roll = (double) roll;
    currentPosition.heading = (double) heading;
  }

}
